package mybatis.generator;


import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.generator.config.rules.DateType;

import java.io.File;
import java.util.*;

/**
 * 代码生成器
 */
public class CodeGenerator {

    /**
     * 配置文件 修改后有时打不进target 用静态
     */
    public static final boolean FILE_OVER_WRITE = true;
    public static final String OUTPUT_DIR="paw-generator/src/main/java";
    public static final String PACKAGE_NAME="com.tg.paw";
    public static final String MODULE="ums";
    public static final String TABLE_NAMES="ums_role_permission_relation";
    public static final String TABLE_PREFIX="ums_";

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        Configuration config = getConfig();

        String packageName = PACKAGE_NAME;
        String module = MODULE;
        String inputOutputDir = OUTPUT_DIR;
        String[] tableNames = TABLE_NAMES.split(",");

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        // 设置主键类型
        globalConfig.setIdType(IdType.ASSIGN_ID);

        // 修改时间类型 java.util.Date
        globalConfig.setDateType(DateType.ONLY_DATE);
        String projectPath = System.getProperty("user.dir");


        String outputDir = inputOutputDir;
        if(isRelativePath(outputDir)){
            outputDir = projectPath+File.separator+outputDir;
        }
        globalConfig.setOutputDir(outputDir);
        String author = config.getString("author");
        if(StringUtils.isNotBlank(author)){
            globalConfig.setAuthor(author);
        }
        globalConfig.setOpen(false);
        // 实体属性 Swagger2 注解
        boolean swaggerEnable = config.getBoolean("swagger2",false);
        globalConfig.setSwagger2(swaggerEnable);

        // mapper.xml
        globalConfig.setBaseColumnList(true);
        globalConfig.setBaseResultMap(true);
        globalConfig.setBaseColumnList(true);

        // 覆盖文件
        globalConfig.setFileOverride(FILE_OVER_WRITE);

        mpg.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        String datasourceUrl = config.getString("datasource.url");
        dsc.setUrl(datasourceUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName(config.getString("datasource.driver-class-name"));
        dsc.setUsername(config.getString("datasource.username"));
        dsc.setPassword(config.getString("datasource.password"));
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig packageConfig = new PackageConfig();

        packageConfig.setModuleName(module);
        packageConfig.setParent(packageName);
        mpg.setPackageInfo(packageConfig);

        // 自定义配置

        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";
//         如果模板引擎是 velocity
         String routeTemplatePath = "/templates/route.ts.vm";
         String listVueTemplatePath = "/templates/list.vue.vm";
         String mockTsTemplatePath = "/templates/_mock.ts.vm";
         String serviceTemplatePath = "/templates/service.ts.vm";
         String indexTemplatePath = "/templates/index.tsx.vm";
         String dataDTemplatePath = "/templates/data.d.ts.vm";
         String createFormTemplatePath = "/templates/CreateForm.tsx.vm";
         String updateFormTemplatePath = "/templates/UpdateForm.tsx.vm";



        // 自定义输出配置
        String modulePath = StringUtils.isNotEmpty(MODULE)? "/"+module : "";
        List<FileOutConfig> focList = new ArrayList<>();
        String webDir = outputDir+ "/pages" + modulePath +"/";
        String outPath = outputDir;
        // 自定义配置会被优先输出
        // xxApi.js
        focList.add(new FileOutConfig(routeTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName+"/" + "route.ts";
            }
        });
        focList.add(new FileOutConfig(mockTsTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName +"/" + "_mock.ts";
            }
        });
        focList.add(new FileOutConfig(indexTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName+"/" +"index.tsx";
            }
        });
        focList.add(new FileOutConfig(dataDTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName+"/" +entityName+"Data.d.ts";
            }
        });
        focList.add(new FileOutConfig(serviceTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName+"/" +entityName+"Service.ts";
            }
        });

        focList.add(new FileOutConfig(createFormTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName+"/components/" +entityName+"CreateForm.tsx";
            }
        });

        focList.add(new FileOutConfig(updateFormTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                String entityName =  firstToLowerCase(tableInfo.getEntityName());
                return webDir + entityName+"/components/" +entityName+"UpdateForm.tsx";
            }
        });

//        //xxList.vue
//        focList.add(new FileOutConfig(listVueTemplatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                return webDir + "/views/"+module+"/"+ tableInfo.getEntityName() + "List.vue";
//            }
//        });



        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */



//        mpg.setCfg(cfg);

        // 自定义属性
        boolean securityEnable = config.getBoolean("security-enable",true);
        InjectionConfig injectionConfig = new InjectionConfig() {
            //自定义属性注入:abc
            //在.ftl(或者是.vm)模板中，通过${cfg.abc}获取属性
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("securityEnable", securityEnable);
                this.setMap(map);
            }
        };

        injectionConfig.setFileOutConfigList(focList);

        //  是否覆盖文件
        injectionConfig.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                File file = new File(filePath);
                boolean exist = file.exists();
                if (!exist) {
                    file.getParentFile().mkdirs();
                }
                if(FILE_OVER_WRITE){
                    return true;
                }
                return !exist;
            }
        });

        //配置自定义属性注入
        mpg.setCfg(injectionConfig);


        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

//        templateConfig.setXml("mapper");
        mpg.setTemplate(templateConfig);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父实体类
        String superEntityClass = config.getString("super-entity-class");
        if(StringUtils.isNotBlank(superEntityClass)){
            strategy.setSuperEntityClass(superEntityClass);
        }
        // 公共父mapper
        String superMapperClass = config.getString("super-mapper-class");
        if(StringUtils.isNotBlank(superMapperClass)){
            strategy.setSuperMapperClass(superMapperClass);
        }
        // 公共父mapper
        String superServiceClass = config.getString("super-service-class");
        if(StringUtils.isNotBlank(superServiceClass)){
            strategy.setSuperServiceClass(superServiceClass);
        }
        // 公共父类
        String superControllerClass = config.getString("super-controller-class");
        if(StringUtils.isNotBlank(superControllerClass)){
            strategy.setSuperControllerClass(superControllerClass);
        }

        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(tableNames);
//        strategy.setControllerMappingHyphenStyle(true);
        strategy.setCapitalMode(true);
        strategy.setLogicDeleteFieldName("delete_status");
        List<TableFill> fillList = new ArrayList<>();
        TableFill createTimeFill = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTimeFill = new TableFill("update_time", FieldFill.UPDATE);
        TableFill creatorFill = new TableFill("creator", FieldFill.INSERT);
        TableFill modifierFill = new TableFill("modifier", FieldFill.UPDATE);
        fillList.add(createTimeFill);
        fillList.add(updateTimeFill);
        fillList.add(creatorFill);
        fillList.add(modifierFill);

        strategy.setTableFillList(fillList);


        // 实体表字段注解 isEntityTableFieldAnnotationEnable
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setTablePrefix(TABLE_PREFIX);
        mpg.setStrategy(strategy);

        String templateEngine = config.getString("template-engine","").trim();
        if("freemarker".equals(templateEngine)){
            // freemarker 模板
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        }
        mpg.execute();
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败，", e);
        }
    }

    /**
     * 相对路径
     * @param path
     * @return
     */
    public static boolean isRelativePath(String path){
        if(StringUtils.isBlank(path)){
            return true;
        }
        if(path.contains(":\\")||path.contains(":/")){
            return false;
        }
        // linux / 开始为根目录
        if(path.startsWith("/") && "/".equals(File.separator)){
            return false;
        }

        return true;
    }

    public static String firstToLowerCase(String name){
        if(StringUtils.isNotEmpty(name)){
            name = name.substring(0,1).toLowerCase()+name.substring(1);
        }
        return  name;
    }
}
